package org.nfyszny.zzzs.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.nfyszny.zzzs.modules.constant.CertificateConstant;
import org.nfyszny.zzzs.modules.constant.ExamineConstant;
import org.nfyszny.zzzs.modules.constant.ReCordConstant;
import org.nfyszny.zzzs.modules.entity.ZzzsCertificate;
import org.nfyszny.zzzs.modules.entity.ZzzsExamine;
import org.nfyszny.zzzs.modules.entity.ZzzsRecordEnterprise;
import org.nfyszny.zzzs.modules.mapper.ZzzsRecordEnterpriseMapper;
import org.nfyszny.zzzs.modules.service.IZzzsCertificateService;
import org.nfyszny.zzzs.modules.service.IZzzsExamineService;
import org.nfyszny.zzzs.modules.service.IZzzsRecordEnterpriseService;
import org.nfyszny.zzzs.modules.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description: 企业备案
 * @Author: jeecg-boot
 * @Date: 2022-11-11
 * @Version: V1.0
 */
@Service
public class ZzzsRecordEnterpriseServiceImpl extends ServiceImpl<ZzzsRecordEnterpriseMapper, ZzzsRecordEnterprise> implements IZzzsRecordEnterpriseService {
    @Autowired
    private ISysDepartService departService;
    @Autowired
    private ISysUserDepartService userService;
    @Lazy
    @Autowired
    private IZzzsExamineService examineService;


    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private IZzzsCertificateService certificateService;


    @Transactional
    @Override
    public void saveRecordEnterpriseInfo(ZzzsRecordEnterprise zzzsRecordEnterprise) {


        //2、进行备案记录新增
        zzzsRecordEnterprise.setIsLogout(ReCordConstant.iterationEnum.LOGOUT_YES.getCode());
        zzzsRecordEnterprise.setStatus(ReCordConstant.RecordEnum.RECORD_CHECK.getCode());
        LoginUser userInfo = UserUtils.getUserInfo();
        System.out.println("userInfo = " + userInfo);
        //分配审批人

        SysDepart sysDepart = departService.queryCompByOrgCode(userInfo.getOrgCode());
        List<SysDepart> sysDeparts = departService.queryDeptByPid(sysDepart.getId());

        //找出监管部门
        SysDepart sysDepart1 = sysDeparts.stream().filter(item -> {
            return item.getOrgCategory().equals("3");
        }).findAny().get();
        SysUserDepart user = userService.getUserByDeptId(sysDepart1.getId());
        if (user != null) {
            zzzsRecordEnterprise.setApproverId(user.getUserId());
        }

        this.saveOrUpdate(zzzsRecordEnterprise);
        //在审批表中插入记录
        ZzzsExamine zzzsExamine = new ZzzsExamine();
        zzzsExamine.setRecordId(zzzsRecordEnterprise.getId());
        zzzsExamine.setRecordType(ExamineConstant.RecordType.ENTERPRISE_RECORD.getCode());
        zzzsExamine.setExaminePerson(user.getUserId());
        zzzsExamine.setExamineStatus(ExamineConstant.StatusEnum.CHECK_STATUS.getCode());
        examineService.save(zzzsExamine);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //过期前30分钟基于提醒
        redisTemplate.opsForValue().set(zzzsExamine.getId() + "_" + format.format(new Date()) + "_" + user.getUserId() + "_企业_message", "", 2 * 24 * 60 - 30, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(zzzsExamine.getId() + "_" + format.format(new Date()) + "_" + user.getUserId() + "_企业_exceed", "", 2, TimeUnit.DAYS);
    }


    @Override
    public Map<String, Object> getEnterpriseStatus() {

        QueryWrapper<ZzzsRecordEnterprise> wrapper = new QueryWrapper<>();
        LoginUser userInfo = UserUtils.getUserInfo();
        //只能查询自己部门的信息
        wrapper.eq("sys_org_code", userInfo.getOrgCode());
        //创建返回对象
        Map<String, Object> map = new HashMap<>();
        List<ZzzsRecordEnterprise> zzzsRecordEnterprises = baseMapper.selectList(wrapper);
        if (zzzsRecordEnterprises.size() == 0) {
            map.put("status", true);
        } else {
            List<ZzzsRecordEnterprise> collect = zzzsRecordEnterprises.stream().filter(item -> {
                //统计审批失败的次数
                return item.getStatus() == ReCordConstant.RecordEnum.RECORD_ERROR.getCode();


            }).collect(Collectors.toList());
            //如果为创建失败状态则还是显示页面
            map.put("status", collect.size() != 0);
            //如果公司审批属于新建状态则返回信息
            List<ZzzsRecordEnterprise> createList = zzzsRecordEnterprises.stream().filter(item -> {
                if (item.getStatus() == ReCordConstant.RecordEnum.RECORD_CREATE.getCode()) {
                    return true;
                }
                return false;
            }).collect(Collectors.toList());
            System.out.println("createList = " + createList);
            //如果有记录则证明处于新建状态
            if (createList.size() != 0) {
                map.put("recordEnterprise", createList.get(0));
                map.put("status", true);
            }

        }
        return map;

    }

    @Override
    public IPage<ZzzsRecordEnterprise> getListByCompanyId(QueryWrapper<ZzzsRecordEnterprise> queryWrapper, Page<ZzzsRecordEnterprise> page) {


        Page<ZzzsRecordEnterprise> enterprisePage = this.page(page, queryWrapper);
        return enterprisePage;
    }

    @Override
    public void saveFiling(ZzzsRecordEnterprise zzzsRecordEnterprise) {
        //2、进行备案记录新增
        zzzsRecordEnterprise.setIsLogout(ReCordConstant.iterationEnum.LOGOUT_YES.getCode());
        zzzsRecordEnterprise.setStatus(ReCordConstant.RecordEnum.RECORD_CREATE.getCode());
        baseMapper.insert(zzzsRecordEnterprise);
    }

    @Override
    public Boolean getEnterpriseSuccessStatus() {

        LoginUser userInfo = UserUtils.getUserInfo();
        QueryWrapper<ZzzsRecordEnterprise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sys_org_code", userInfo);
        queryWrapper.eq("status", ReCordConstant.RecordEnum.RECORD_SUCCESS.getCode());
        ZzzsRecordEnterprise one = baseMapper.selectOne(queryWrapper);
        return one != null;
    }

    @Override
    @Transactional
    public void change(ZzzsRecordEnterprise zzzsRecordEnterprise) {
        //先将上一条备案信息隐藏
        ZzzsRecordEnterprise record = new ZzzsRecordEnterprise();
        record.setId(zzzsRecordEnterprise.getId());
        record.setIsLogout(ReCordConstant.iterationEnum.LOGOUT_NO.getCode());
        System.out.println("record = " + record);
        int i = baseMapper.updateIsDeleteById(record);
        System.out.println("i = " + i);
        //再将重新备案的id设置为null
        zzzsRecordEnterprise.setId(null);
        this.saveRecordEnterpriseInfo(zzzsRecordEnterprise);
        //将证书表对应的备案id改成新的备案id
        ZzzsCertificate certificate = certificateService.getOne(new QueryWrapper<ZzzsCertificate>().eq("certificate_id", record.getId()));
        certificate.setCertificateId(zzzsRecordEnterprise.getId());
        certificate.setStatus(CertificateConstant.CertificateStatus.INVALID.getCode());
        certificateService.updateById(certificate);


    }

    @Override
    @Transactional
    public void review(ZzzsRecordEnterprise zzzsRecordEnterprise) {
        //先将上一条备案信息隐藏
        ZzzsRecordEnterprise record = new ZzzsRecordEnterprise();
        record.setId(zzzsRecordEnterprise.getId());
        record.setIsLogout(ReCordConstant.iterationEnum.LOGOUT_NO.getCode());
        System.out.println("record = " + record);
        int i = baseMapper.updateIsDeleteById(record);
        System.out.println("i = " + i);
        //再将重新备案的id设置为null
        zzzsRecordEnterprise.setId(null);
        this.saveRecordEnterpriseInfo(zzzsRecordEnterprise);
        //将证书表对应的备案id改成新的备案id
        ZzzsCertificate certificate = certificateService.getOne(new QueryWrapper<ZzzsCertificate>().eq("certificate_id", record.getId()));
        certificate.setCertificateId(zzzsRecordEnterprise.getId());
        certificate.setStatus(CertificateConstant.CertificateStatus.GIVEN_OUT.getCode());
        certificateService.updateById(certificate);


    }

    @Override
    public ZzzsRecordEnterprise getHaveInfoById(String id) {


        return baseMapper.getHaveInfoById(id);
    }

}
